package cn.tedu.shoppingmall.controller;

import cn.tedu.shoppingmall.mapper.*;
import cn.tedu.shoppingmall.vo.*;
import cn.tedu.shoppingmall.vo.Class;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
@Api(tags = "3商城模块")
@RestController
public class AdminMallController {
    @Autowired(required = false)
    ClassMapper clsmapper;
    @Autowired(required = false)
    CommodityMapper commapper;


    @Value("${dirPath}")
    private String dirPath;


    @Autowired
    CommentMapper commentMapper;


    @Autowired
    ReportClsMapper reportClsMapper;
    @Autowired
    UserMapper userMapper;

    //查商品所有信息
    //需求:做成分页查询
    //第一步,把返回值类型pageInfo<[你要返回的实体类型]>
    @GetMapping("/admin/selectToCommodityLimit")
    public PageInfo<Commodity> selectToCommodityLimit(Integer pageNum) {
        return selectToCommodityLimit(pageNum,9);
    }
    @GetMapping("/admin/selectToCommodityLimitandNum")
    public PageInfo<Commodity> selectToCommodityLimit(Integer pageNum,Integer pageSize) {
        if (pageNum==0) {pageNum=1;}
        PageHelper.startPage(pageNum,pageSize);
        List<Commodity> list = commapper.select();
        PageInfo<Commodity> pageInfo = new PageInfo<Commodity>(list,6);
        return pageInfo;
    }

    //查商品所有信息
    @RequestMapping("/admin/selectToCommodity")
    public List<Commodity> selectToCommodity() {
        return commapper.select();
    }

    //通过clsid查单类商品信息
    @RequestMapping("/admin/selectToCommodityByClsid")
    public List<Commodity> commoditySelectByClsid(int id) {
        return commapper.SelectByClsid(id);
    }

    //查所有类信息
    @RequestMapping("/admin/selectToClass")
    public List<Class> selectToClass() {
        //想加缓存来着,,失败了,返回的是Map,还得改大量代码,不弄了
//        if (cache.getComClsCache().isEmpty()){
//            List<Class> classes =
//            for (Class c : classes){
//                cache.getComClsCache().put(c.getName(),c);
//            }
//            return cache.getComClsCache().get()
//
//        }
        return clsmapper.select();
    }

    //商品查看加一
    @PostMapping("/admin/ShownumAdd/{id}")
    public String commoditySearchnumAdd(@PathVariable Integer id) {
        commapper.UpdateToCommodityShownumAdd(id);
        return "ok";
    }
    @Autowired
    ImgsMapper imgsMapper;
    //通过id查单个商品信息
    @RequestMapping("/admin/commoditySelectById")
    public Commodity commoditySelectById(Integer id) {
        Commodity commodity = commapper.SelectById(id);
        if (commapper.SelectToIdByComid(id) != null) {
            Images imgs = imgsMapper.SelectToIImgsByComId(id);
//        Map<String,String>
            List<String> list = new ArrayList<>();
            if (imgs.getUrl1() != null) list.add(imgs.getUrl1());
            if (imgs.getUrl2() != null) list.add(imgs.getUrl2());
            if (imgs.getUrl3() != null) list.add(imgs.getUrl3());
            if (imgs.getUrl4() != null) list.add(imgs.getUrl4());
            if (imgs.getUrl5() != null) list.add(imgs.getUrl5());
            if (imgs.getUrl6() != null) list.add(imgs.getUrl6());
            if (imgs.getUrl7() != null) list.add(imgs.getUrl7());
            if (imgs.getUrl8() != null) list.add(imgs.getUrl8());
            if (imgs.getUrl9() != null) list.add(imgs.getUrl9());
            if (imgs.getUrl10() != null) list.add(imgs.getUrl10());
            commodity.setUrls(list);
        }
        return commodity;
    }

    //通过id查单个商品的附属评论
    @RequestMapping("/admin/commentSelectById")
    public List<Comment> commentSelectById(int comid){
        return commentMapper.findAll(comid);
    }

    //添加评论
    @RequestMapping("/admin/addcomment")
    public String addcomment(Comment comment,MultipartFile picFile, @AuthenticationPrincipal UserDetails user){
        System.out.println("comment = " + comment + ", picFile = " + picFile + ", user = " + user);
        if (!picFile.isEmpty()) {
            String fileName = picFile.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID() + suffix;
            //文件夹路径
            SimpleDateFormat f = new SimpleDateFormat("/yyyy/MM/dd/");
            //new Date()当前系统时间  /2021/12/20/
            String datePath = f.format(new Date());
            File dirFile = new File(dirPath + datePath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            //文件完整路径
            String filePath = dirPath + datePath + fileName;
            try {
                //保存文件
                picFile.transferTo(new File(filePath));
            } catch (IOException e) {
                System.out.println("URL装配失败，请检查路径");
            }
            System.out.println("datePath+filePath = " + datePath+filePath);
            comment.setUrl(datePath + fileName);
        }
        User userold = userMapper.selectByUsername(user.getUsername());
        UserDetail user1 = userMapper.selectByUserid(userold.getId());
        comment.setUsernick(user1.getNick())
                        .setUserurl(user1.getUrl());
        System.out.println("comment11111111 = " + comment);
        commentMapper.insert(comment);
        return "ok";
    }



    //更新商品
    @RequestMapping("/admin/commodityupdate")
    public void commodityupdate(Commodity com, Integer id, MultipartFile picFile) {
        //如果未填写,则默认原来不变
        Commodity comOld = commapper.SelectById(id);
        if (com.getName() == null || "".equals(com.getName())) {
            com.setName(comOld.getName());
        }
        if (com.getSum() == null) {
            com.setSum(comOld.getSum());
        }
        if (com.getSalesnum() == null) {
            com.setSalesnum(comOld.getSalesnum());
        }
        if (com.getPrice() == null) {
            com.setPrice(comOld.getPrice());
        }
        if (com.getIntro() == null || "".equals(com.getIntro())) {
            com.setIntro(comOld.getIntro());
        }
        if (com.getClassId() == 0) {
            com.setClassId(comOld.getClassId());
        }
        if (!picFile.isEmpty()) {
            String fileName = picFile.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID() + suffix;
            //文件夹路径
            SimpleDateFormat f = new SimpleDateFormat("/yyyy/MM/dd/");
            //new Date()当前系统时间  /2021/12/20/
            String datePath = f.format(new Date());
            File dirFile = new File(dirPath + datePath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            //文件完整路径
            String filePath = dirPath + datePath + fileName;
            try {
                //保存文件
                picFile.transferTo(new File(filePath));
            } catch (IOException e) {
                System.out.println("URL装配失败，请检查路径");
            }
            com.setUrl(datePath + fileName);
        } else {
            com.setUrl(comOld.getUrl());
        }

        commapper.update(com);
    }

    //添加商品
    @RequestMapping("/admin/commodityinsert")
    public void commodityinsert(Commodity com, MultipartFile picFile) {
        if (!picFile.isEmpty()) {
            String fileName = picFile.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID() + suffix;
            //文件夹路径
            SimpleDateFormat f = new SimpleDateFormat("/yyyy/MM/dd/");
            //new Date()当前系统时间  /2021/12/20/
            String datePath = f.format(new Date());
            File dirFile = new File(dirPath + datePath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            //文件完整路径
            String filePath = dirPath + datePath + fileName;
            try {
                //保存文件
                picFile.transferTo(new File(filePath));
            } catch (IOException e) {
                System.out.println("URL装配失败，请检查路径");
            }
            com.setUrl(datePath + fileName);//把包含日期路径的图片路径封装
        }

        commapper.insert(com);
    }

    //添加商品类
    @RequestMapping("/admin/addCls")
    public void addCls(AddCls cls, MultipartFile picFile) {
        System.out.println("cls = " + cls + ", picFile = " + picFile);
        if (!picFile.isEmpty()) {
            String fileName = picFile.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID() + suffix;
            //文件夹路径
            SimpleDateFormat f = new SimpleDateFormat("/yyyy/MM/dd/");
            //new Date()当前系统时间  /2021/12/20/
            String datePath = f.format(new Date());
            File dirFile = new File(dirPath + datePath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            //文件完整路径
            String filePath = dirPath + datePath + fileName;
            try {
                //保存文件
                picFile.transferTo(new File(filePath));
            } catch (IOException e) {
                System.out.println("URL装配失败，请检查路径");
            }
            cls.setUrl(datePath + fileName);//把包含日期路径的图片路径封装
        }
        if (cls.getClassId() != null) {
            if (cls.getClassId() == 1) {
                clsmapper.addCls(cls);
            } else if (cls.getClassId() == 2) {
                reportClsMapper.addReportCls(cls);
            }
        }
    }


    //删除商品
    @RequestMapping("/admin/CommodityDelete")
    public void CommodityDelete(int id) {
        commapper.delete(id);
    }

    //搜索商品
    @RequestMapping("/admin/CommoditySearch")
    public List<Commodity> CommodityDelete(String content) {
        if (content == null || "".equals(content) || "undefined".equals(content)) {
            return null;
        }
        List<Commodity> lists = commapper.SelectSearch(content);
        if (!lists.isEmpty()) {
            for (Commodity c : lists) {
                //商品被搜索次数
                commapper.UpdateToCommoditySearchnumAdd(c.getId());
            }
        }

        return commapper.SelectSearch(content);

    }

    //添加多图片,,MultipartFile[]不能用,就先放着吧,荒废了

//    //添加多图片
//    @RequestMapping("/admin/addimgs")
//    public void addimgs(Integer comid, MultipartFile picFile1, MultipartFile picFile2, MultipartFile picFile3
//            , MultipartFile picFile4, MultipartFile picFile5, MultipartFile picFile6, MultipartFile picFile7
//            , MultipartFile picFile8, MultipartFile picFile9, MultipartFile picFile10) {
//        System.out.println("comid = " + comid + ", picFile1 = " + picFile1 + ", picFile2 = " + picFile2 + ", picFile3 = " + picFile3 + ", picFile4 = " + picFile4 + ", picFile5 = " + picFile5 + ", picFile6 = " + picFile6 + ", picFile7 = " + picFile7 + ", picFile8 = " + picFile8 + ", picFile9 = " + picFile9 + ", picFile10 = " + picFile10);
//        Images images = new Images();
//        images.setComid(comid);
//        //用map接收值,再给imgs传值
//        Map<String,MultipartFile> urlMap = new HashMap<>();
//        urlMap.put("url1",picFile1);
//        urlMap.put("url2",picFile2);
//        urlMap.put("url3",picFile3);
//        urlMap.put("url4",picFile4);
//        urlMap.put("url5",picFile5);
//        urlMap.put("url6",picFile6);
//        urlMap.put("url7",picFile7);
//        urlMap.put("url8",picFile8);
//        urlMap.put("url9",picFile9);
//        urlMap.put("url10",picFile10);
//        //待会将名字url存进集合
//        List<String> urls = new ArrayList<>();
//        //判断不为空
//        for (int i=1;i<11;i++) {
//            if (!urlMap.get("url"+1).isEmpty()) {
//                String fileName = urlMap.get("url"+1).getOriginalFilename();
//                String suffix = fileName.substring(fileName.lastIndexOf("."));
//                fileName = UUID.randomUUID() + suffix;
//                //文件夹路径
//                SimpleDateFormat f = new SimpleDateFormat("/yyyy/MM/dd/");
//                //new Date()当前系统时间  /2021/12/20/
//                String datePath = f.format(new Date());
//                File dirFile = new File(dirPath + datePath);
//                if (!dirFile.exists()) {
//                    dirFile.mkdirs();
//                }
//                //文件完整路径
//                String filePath = dirPath + datePath + fileName;
//                try {
//                    //保存文件
//                    urlMap.get("url"+i).transferTo(new File(filePath));
//                } catch (IOException e) {
//                    System.out.println("URL装配失败，请检查路径");
//                }
//                urls.add(datePath + fileName);
//            }
//            urls.add("");
//        }
//        //赋值
//        images.setUrl1(urls.get(0))
//                .setUrl2(urls.get(1))
//                .setUrl3(urls.get(2))
//                .setUrl4(urls.get(3))
//                .setUrl5(urls.get(4))
//                .setUrl6(urls.get(5))
//                .setUrl7(urls.get(6))
//                .setUrl8(urls.get(7))
//                .setUrl9(urls.get(8))
//                .setUrl10(urls.get(9));
//
//        commapper.insertImgs(images);
//    }
}
